//
//  InvestmentDetailViewController.m
//  SP2P
//
//  Created by 吴建东 on 16/6/2.
//  Copyright © 2016年 EIMS. All rights reserved.
//

#import "InvestmentDetailViewController.h"
#import "InvestmentBriefView.h"
#import "ProgressLayer.h"
#import "SetPayPasswordViewController.h"
#import "CommonWebViewController.h"
#import "SQBRechargeViewController.h"
#import "AddBankCardViewController.h"
#import "ShouYiView.h"
#import "InvesmentProductNameViewController.h"
#import "InvesmentSureViewController.h"
@interface InvestmentDetailViewController ()<UIScrollViewDelegate,UITableViewDelegate,UITableViewDataSource,UITextFieldDelegate,HTTPClientDelegate,UIAlertViewDelegate> {
    
    UIScrollView *_detailScrollView;
    ProgressLayer *_progressLayer;
    
    double _balance;    //账户余额
    NSString *_MonthAcount;  //几个月
    InvestmentBriefView *_briefView; //查看详情
    
    NSString *_signStr; //投标所需标识符
}
@property (weak, nonatomic  ) IBOutlet UIImageView   *backImageView;
@property (weak, nonatomic) IBOutlet UILabel *rateValue;
@property (weak, nonatomic  ) IBOutlet ProgressLayer *layerView;
@property (weak, nonatomic  ) IBOutlet UILabel       *rateLabel;
@property (weak, nonatomic  ) IBOutlet UILabel       *minTenderLabel;
@property (strong, nonatomic) IBOutlet UIView        *headerView;
@property (weak, nonatomic  ) IBOutlet UILabel       *amountLabel;
@property (weak, nonatomic) IBOutlet UILabel *amountValue;
@property (weak, nonatomic) IBOutlet UILabel *tenderAmountValue;
@property (weak, nonatomic) IBOutlet UILabel *moneyTypeValue;
@property (weak, nonatomic) IBOutlet UILabel *prodectDescVaue;
@property (weak, nonatomic  ) IBOutlet UITextField   *tenderAmountTextField;
@property (weak, nonatomic  ) IBOutlet ClickButton   *tenderButton;
@property (strong, nonatomic) IBOutlet UIView        *footerView;

@property (nonatomic, strong) UIScrollView   *contentScrollView;
@property (nonatomic, strong) UITableView    *tableView;
@property (nonatomic,strong) ShouYiView *shouView;
@property (nonatomic, strong) NetWorkClient *requestClient;
@property (nonatomic, assign) NSInteger     requestType;
@property (nonatomic, assign) BOOL          isLoading;

@end

@implementation InvestmentDetailViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    [self setNavBarBackgroundColor:[UIColor clearColor] andStatusBar:UIStatusBarStyleLightContent];
    
    [self initNavBarTitle:_naviTitle andLeftItemName:@"返回" andRightItemName:@"项目详情"];
    
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    
    [self setNavBarBackgroundColor:KColor andStatusBar:UIStatusBarStyleLightContent];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    [self initData];
    [self initView];
   [AppDelegateInstance.window addSubview:self.shouView];

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(requestData) name:@"RechargeSuccess" object:nil];
}

- (void)back {
    [self.navigationController popViewControllerAnimated:YES];
}


#pragma mark - Action
- (void)rightBarButtonClick{
    InvesmentProductNameViewController *pnVC = [[InvesmentProductNameViewController alloc] init];
    [self.navigationController pushViewController:pnVC animated:YES];
    
}
- (IBAction)tendetButtonClick:(id)sender {
    if (AppDelegateInstance.userInfo.realName.length<=0 || !AppDelegateInstance.userInfo.hasBindCard) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"您尚未进行实名认证" message:@"是否前去实名认证？" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
        alert.tag = 7;
        [alert show];
        return;
    }
    
    if (_tenderAmountTextField.text.doubleValue <= 0) {
        [SVProgressHUD showErrorWithStatus:@"请输入正确的金额"];
        return;
    }
    if (!AppDelegateInstance.userInfo.isPayPasswordStatus) {
        [self showNoTradePasswordAlert];
        return;
    }
    if (_tenderAmountTextField.text.doubleValue > _balance) {
        [self showRechargeAlert];
        return;
    }
    
    InvesmentSureViewController * sureVC = [[InvesmentSureViewController alloc] init];
    sureVC.productName = _naviTitle;
    sureVC.monthStr = _MonthAcount;
    sureVC.balance = _balance;
    sureVC.InvestAmountStr = _tenderAmountTextField.text;
    sureVC.signStr = _signStr;
    [self.navigationController pushViewController:sureVC animated:YES];
    
   
}

- (void)showRechargeAlert {
    
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:[NSString stringWithFormat:@"对不起！您可用余额不足！根据您的余额您最多只能投%.2f元",_balance] delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
    alert.tag = 9;
    [alert show];
}

- (void)showNoTradePasswordAlert {
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"您尚未设置交易密码" message:@"是否前去设置交易密码？" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    alert.tag = 8;
    [alert show];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (alertView.tag==7 && buttonIndex==1) {
        //去实名认证
        AddBankCardViewController *addBankCard = [[AddBankCardViewController alloc] init];
        addBankCard.editType = 1;
        addBankCard.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:addBankCard animated:YES];
    }else if (alertView.tag==8 && buttonIndex==1) {
        //设置交易密码
        SetPayPasswordViewController *setPayPassword = [[SetPayPasswordViewController alloc] init];
        //    changePwd.delegate = self;
        setPayPassword.editType = 1;
        [self.navigationController pushViewController:setPayPassword animated:YES];
    }else if (alertView.tag==9 && buttonIndex==0) {
        [self keyboardHidden];
        
        SQBRechargeViewController *recharge = [[SQBRechargeViewController alloc] initWithNibName:@"SQBRechargeViewController" bundle:nil];
        recharge.viewType = 1;
        [self.navigationController pushViewController:recharge animated:YES];
    }
}

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
    
    return YES;
}

- (IBAction)checkMoreDetailTap:(id)sender {
    UIScrollView *scrollView = [self.view viewWithTag:6];
    
    [scrollView setContentOffset:CGPointMake(0, MSHIGHT) animated:YES];
}


- (void)textFieldValueChanged {
    if (_tenderAmountTextField.text.doubleValue>0) {
        [CommonClass buttonEnableWithButton:_tenderButton enable:YES];
    }else {
        [CommonClass buttonEnableWithButton:_tenderButton enable:NO];
    }
}

- (void)keyboardHidden {
    if (_tenderAmountTextField.isFirstResponder) {
        [_tenderAmountTextField resignFirstResponder];
    }
}



//计算收益
- (IBAction)calculateEarningsClick:(id)sender {
    
    [self show];
}
- (void)show{
    
    [UIView animateWithDuration:2.0 animations:^{
        
        self.shouView.hidden = NO;
    }];
    
    
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    if (scrollView.contentOffset.y < MSHIGHT/2) {
        [self setNavBarBackgroundColor:[UIColor clearColor] andStatusBar:UIStatusBarStyleLightContent];
    }else {
        [self setNavBarBackgroundColor:KColor andStatusBar:UIStatusBarStyleLightContent];
    }
}


#pragma mark - TableView
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (self.view.frame.size.height > KAdaptNum(420)+KAdaptNum(45)) {
        return 1;
    }
    return 0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *cellID = @"cellId";
    UITableViewCell *cell = [_tableView dequeueReusableCellWithIdentifier:cellID];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.backgroundColor = KbackgroundColor;
    }
    
    cell.frame=CGRectMake(cell.frame.origin.x, cell.frame.origin.y, cell.frame.size.width, self.view.frame.size.height - KAdaptNum(420) - KAdaptNum(45));
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return [self tableView:tableView cellForRowAtIndexPath:indexPath].frame.size.height;
}

#pragma mark - Data
- (void)initData {
    
    [self requestData];
}

- (void)requestData {
    _requestType = 1;
    
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    [parameters setObject:@"507" forKey:@"OPT"];
    [parameters setObject:@"" forKey:@"body"];
    [parameters setObject:AppDelegateInstance.userInfo.userId forKey:@"userId"];
    [parameters setObject:_investmentId forKey:@"planId"];
    
    if (_requestClient == nil) {
        _requestClient = [[NetWorkClient alloc] init];
        _requestClient.delegate = self;
    }
    [_requestClient requestGet:@"app/services" withParameters:parameters];
}


- (void)startRequest {
    _isLoading = YES;
}

- (void)httpResponseSuccess:(NetWorkClient *)client dataTask:(NSURLSessionDataTask *)task didSuccessWithObject:(id)obj {
    [SVProgressHUD dismiss];
    _isLoading = NO;
    NSDictionary *dics=(NSDictionary *)obj;
    DLOG(@"--%@",dics);
    NSString *errorStr=[NSString stringWithFormat:@"%@",[dics objectForKey:@"error"]];
    if ([errorStr isEqualToString:@"-1"]) {
        if (_requestType == 1) {
            [_progressLayer setPercent:75.0 animated:YES];
            
            _balance = [[dics objectForKey:@"balance"] doubleValue];
            _amountLabel.text = [NSString stringWithFormat:@"%@ 元",[CommonClass formatConversion:_balance type:0]];
            NSDictionary *planDict = [dics objectForKey:@"plan"];
            _MonthAcount = [planDict objectForKey:@"period"];
            _minTenderLabel.text = [NSString stringWithFormat:@"%@个月起投，多重保障",[planDict objectForKey:@"period"]];
            _rateLabel.text = [NSString stringWithFormat:@"%.1f",[[planDict objectForKey:@"apr"] floatValue]];
            
            _signStr = [NSString stringWithFormat:@"%@",planDict[@"sign"]];
            
            NSString *description = [NSString stringWithFormat:@"%@",dics[@"description"]];
            description = [CommonClass filterHTML:description];
            
            _briefView.descriptionStr = description;
            
        }
}
}
- (void)httpResponseFailure:(NetWorkClient *)client dataTask:(NSURLSessionDataTask *)task didFailWithError:(NSError *)error {
    _isLoading = NO;
    [SVProgressHUD dismiss];
}

- (void) networkError {
    _isLoading = NO;
    [SVProgressHUD dismiss];
}


#pragma mark - View
- (void)initView {
    [self loadLayerView];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFieldValueChanged) name:UITextFieldTextDidChangeNotification object:_tenderAmountTextField];
    
    UIScrollView *contentScrollView = [UIScrollView scrollViewWithFrame:RECTMAKE(0, 0, MSWIDTH, MSHIGHT) delegate:self backgroundColor:KbackgroundColor superview:self.view];
    contentScrollView.pagingEnabled = YES;
    contentScrollView.bounces = NO;
    contentScrollView.contentSize = CGSizeMake(0, MSHIGHT*2);
    contentScrollView.tag = 6;
    
    _minTenderLabel.font = KFontSize(12);
    _rateValue.font = KFontSize(10);
    _rateLabel.font = KFontSize(30);
    _amountValue.font = KFontSize(14);
    _amountLabel.font = KFontSize(14);
    _tenderAmountValue.font = KFontSize(14);
    _tenderAmountTextField.font = KFontSize(14);
    _moneyTypeValue.font = KFontSize(14);
    _tenderButton.titleLabel.font = KFontSize(15);
    _prodectDescVaue.font = KFontSize(13);
    
    _headerView.frame = RECTMAKE(0, 0, MSWIDTH, KAdaptNum(420));
    _footerView.frame = RECTMAKE(0, 0, MSWIDTH, KAdaptNum(45));
    
    _tableView = [UITableView tableViewWithFrmae:RECTMAKE(0, 0, MSWIDTH, MSHIGHT) backgroundColor:KbackgroundColor delegate:self dataSource:self tableViewStyle:UITableViewStylePlain separatorStyle:UITableViewCellSeparatorStyleNone superview:contentScrollView];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.tableHeaderView = self.headerView;
    _tableView.tableFooterView = self.footerView;
    _tableView.bounces = NO;
    
    
    _briefView = [[InvestmentBriefView alloc] initWithFrame:RECTMAKE(0, MSHIGHT+64, MSWIDTH, MSHIGHT-64) type:self.viewType];
    [contentScrollView addSubview:_briefView];
    
    _tenderButton.clipsToBounds = YES;
    _tenderButton.layer.cornerRadius = 4.0f;
    if (self.viewType == 1) {
        self.backImageView.image = [UIImage imageNamed:@"investDetail_season_back"];
    }else if (self.viewType == 2) {
        self.backImageView.image = [UIImage imageNamed:@"investDetail_halfyear_back"];
    }else {
        self.backImageView.image = [UIImage imageNamed:@"investDetail_year_back"];
    }
    
}

- (void)loadLayerView {
    CGFloat progressWidth = KAdaptNum(120);
    
    _progressLayer = [[ProgressLayer alloc] initWithFrame:CGRectMake(0, 0, progressWidth, progressWidth) diameter:progressWidth roundWidth:5 start:CGPointMake(-210, 30)];
    [_layerView addSubview:_progressLayer];
    _progressLayer.strokeColor = KColor;
    
}


-(ShouYiView *)shouView{
    if (_shouView == nil) {
        _shouView = [[ShouYiView alloc] initWithFrame:CGRectZero andViewType:self.viewType];
        _shouView.frame = CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height);
        _shouView.hidden = YES;
    }
    return _shouView;

}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
